<script setup lang="ts">
import { onActivated, onDeactivated, ref, defineExpose, defineEmits, defineProps } from "vue"
import dice from "@/components/dice.vue"

const props = defineProps({
    diceNumber: {
        // 骰子数量
        type: Number,
        default: 6,
    },
})

const diceRefs = ref([]) as any // 所有骰子
const hasRotate = ref(false) // 正在摇色子
const showNumber = ref(0) // 摇色子结果
const hasShowNumber = ref(false) // 显示结果
const rotate = () => {
    if (hasRotate.value) return
    hasRotate.value = true
    let resNumbers: number[] = []
    let res = 0
    diceRefs.value
        .filter((i: any) => i != null)
        .forEach((item: any) => {
            item.rotate().then((result: number) => {
                resNumbers.push(result)
                res += result
                if (resNumbers.length === props.diceNumber) {
                    hasShowNumber.value = true
                    showNumber.value = res
                    setTimeout(() => {
                        hasRotate.value = false
                        emit("rotateEnd", res)
                        hasShowNumber.value = false
                        diceRefs.value
                            .filter((i: any) => i != null)
                            .forEach((item: any) => {
                                item.handleHideDice() // 将骰子重置到屏幕上方
                            })
                    }, 1000)
                }
            })
        })
}

const emit = defineEmits(["rotateEnd"])

defineExpose({
    rotate,
})

onActivated(() => {})

onDeactivated(() => {})
</script>

<template>
    <div class="diceList flex items-center" :class="{ show: hasRotate }">
        <dice class="diceListItem" v-for="index in props.diceNumber" :key="index" :ref="(el: any) => diceRefs[index] = el"></dice>
        <div class="number flex items-center justify-center" :class="{ show: hasShowNumber }">
            {{ showNumber }}
        </div>
    </div>
</template>

<style lang="scss">
.diceList {
    width: 100vw;
    height: 100vh;
    justify-content: space-evenly;
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.9);
    opacity: 0;
    transition: all 0.4s;
    pointer-events: none;
    overflow: hidden;
    z-index: 9999;
    // 内阴影
    box-shadow: inset 0 0 5vmin rgba(255, 255, 255, 0.1);
    &.show {
        opacity: 1;
        pointer-events: auto;
    }

    .number {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 30vmin;
        opacity: 0;
        transition: all 0.3s;
        z-index: 999;
        perspective: 100vmin;
        background: linear-gradient(-90deg, #d3eee0, #d3e6f2, #d8dbf7, #f4e8fa);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-family: cute;
        &.show {
            opacity: 1;
            transform: translate(-50%, -50%) scale(2);
        }
    }
}
</style>
